package com.chang.jdbc;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import java.util.List;

@SpringJUnitConfig(locations = "classpath:bean.xml")
public class JDBCTemplateTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testUpdate() {
        // 编写sql
        String sql = "insert into t_emp values(null,?,?,?)";
        Object[] args = {"LANGOU","25","男"};
        int rows = jdbcTemplate.update(sql,args); // 可封装数值，也可设置长参数


        // String sql = "update t_emp set age=? where id=?";
        // Object[] args = {"27",2};

        // String sql = "delete from t_emp  where id=?";

        // 调用jdbcTemplate方法，传参
        // int rows = jdbcTemplate.update(sql,5,3);
        // int rows = jdbcTemplate.update(sql, 3);
        System.out.println("运行完毕,改变行数为:" + rows);
    }

    @Test
    public void selectTest() {

        String sql = "select * from t_emp where id=?";

        // 返回单个对象
        // 方法1
        Emp query = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {  // rs:结果集封装
            Emp emp = new Emp();
            emp.setId(rs.getInt("id"));
            emp.setName(rs.getString("name"));
            emp.setAge(rs.getInt("age"));
            emp.setSex(rs.getString("sex"));
            System.out.println("rowNum:>>>>>>"+rowNum); // 受影响的行数
            return emp;
        }, 1);
        System.out.println("方法1查询结果返回"+query);
        // 方法2
        Emp emp = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Emp.class),1);
        System.out.println("方法2查询结果返回"+emp);
    }

    @Test
    public void selectList(){
        String sql = "select * from t_emp";
        List<Emp> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
        System.out.println("查询表中所有数据:>>>>>"+list);
    }

    @Test
    public void selectValue(){
        String sql = "select count(*) from t_emp";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);  // 第二个参数代表返回类型的class
        System.out.println("查询表中含有多少条数据:>>>>>"+count);
    }

}
